<template name="comment_socket">
	<view>
		<scroll-view class="comment-content-scroll" :class="pStyle" :style="'height:' + pHeight" scroll-y="true" :scroll-top="scrollTop"
		 :scroll-with-animation="true">
			<view class="comment-content">
				<view v-for="(item,index) in list" v-bind:key="index">
					<view class="common-li" :class="item.type">
						<text class="name ">{{item.from_client_name}}：</text>
						<text class="cn" v-html="item.content"> </text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>
<script>
	window["SCHEMETYPE"] = "http";
</script>
<script>
	// #ifdef H5
	var inUser = null

	function init(app, appkey, token, room_id, inu) {
		window.inUser = inu
		inUser = inu
		let _this = this
		let appInfo = {
			'appKey': appkey,
			'token': token
		}
		let chatRoomInfo = {
			"chatRoomId": "gsc3.0-live-" + room_id,
			"count": 20
		}
		app.showNewMessage({
			content: '正在加入聊天室...',
			extra: {
				type: 'system'
			}
		})
		app.emojilist = RongChatRoom.getEmojiList()

		RongChatRoom.init(appInfo, chatRoomInfo, {
			onSuccess: function(chatRoom) {
				app.mchatRoom = chatRoom
				app.getOnline(true)
				//聊天室发消息
				var obj = {
					content: '<span style="color:orange">' + inUser.name + "</span>" + "加入聊天室成功",
					extra: {
						user: inUser,
						type: 'system',
						event: 'join'
					}
				};
				chatRoom.sendMessage(obj, {
					onSuccess: function(message) {
						app.showNewMessage(obj)
					},
					onError: function(errorCode, message) {
						console.log("发送聊天室消息失败", errorCode);
					}
				});
			},
			onError: function(error) {
				console.log('加入聊天室失败。')
				var obj = {
					content: '<span style="color:orange">' + inUser.name + "</span>" + "加入聊天室失败",
					extra: {
						user: inUser,
						type: 'system',
						event: 'join'
					}
				};
				app.showNewMessage(obj)
				// 加入聊天室失败
			},
			onMessage: function(message) {
				// console.log("007");
				// console.log(message);
				if (message.content.content && message.content.extra && message.content.extra.type) {
					// console.log(message);
					app.showNewMessage(message.content)
				}
				if (message.content.extra.event) {
					console.log(message.content.extra.event)
					if (message.content.extra.event == 'join') {
						app.getOnline(false)
					}
				}
				app.showNewMessage("chatroomId: " + message.targetId + ",  messageUId: " + message.messageUId);
			}
		})
	}
	export default {
		name: "comment_socket",
		props: {
			room_id: {
				type: String,
				default: '0'
			},
			pStyle: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				socketStatus: '',
				from_client_id: 0,
				from_client_name: '',
				member: null,
				client_list: [],
				list: [],
				scrollTop: 0,
				pHeight: '300px',
				appkey: 'p5tvi9dspqf44',
				token: '',
				mchatRoom: '',
				loadingonline: false,
				default_count: 0,
				inUser: null,
				emojilist: [],
			}
		},
		destroyed() {
			this.closeSocket()
		},
		created: function(e) {
			let _this = this
			let member = this.$common.getCache('member')
			if (member) {
				this.member = member
			}
		},
		methods: {
			getToken(callback) {
				return new Promise((resolve, reject) => {
					let token = this.$common.getCache('rong-token')
					if (!token) {
						this.$http
							.get('rongim_token')
							.then((response) => {
								// console.log(response)
								this.$common.setCache('rong-token', response.data.data)
								resolve(response.data.data)
							})
							.catch((response) => {
								reject(response)
							})
					} else {
						// this.token = token
						resolve(token)
					}
				})
			},
			loginim(inUser) {
				if (!this.inUser) {
					this.getToken().then((token) => {
						this.inUser = inUser
						init(this, this.appkey, token, this.room_id, inUser)
					})
				}
			},
			getOnline(first) {
				if (this.loadingonline) return
				let _this = this
				this.loadingonline = true
				this.mchatRoom.getInfo({
					order: RongIMLib.GetChatRoomType.REVERSE,
					memberCount: 10
				}, {
					onError(){
						_this.loadingonline = false
					},
					onSuccess(res) {
						console.log(res)
						_this.loadingonline = false
						var length = res.userTotalNums
						if (first || res.userTotalNums < 10) {
							var ids = [];
							for (let p in res.userInfos) {
								var m = res.userInfos[p].id;
								ids.push(m);
							}
							_this.$emit("pClientChange", {
								ids: ids,
								length: length
							})
						} else
							_this.$emit("pClientChange", {
								ids: null,
								length: length
							})

					}
				})
			},
			getEmojiList() {
				return this.emojilist
			},
			getHistory() {},
			onSubmit(content) {
				let _this = this
				// var input = $("#comment-content");
				// var to_client_id = select_client_id;
				// var to_client_name = '';
				var content = content.replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
				// console.log(content)
				if (content != "") {
					var obj = {
						content: content,
						extra: {
							user: this.inUser,
							type: 'say'
						}
					}
					this.mchatRoom.sendMessage(obj, {
						onSuccess: function(message) {
							_this.showNewMessage(obj)

							_this.$common.showSuccess('发送成功')
						},
						onError: function(errorCode, message) {
							console.log("发送聊天室消息失败", errorCode)
						}
					})
					// input.val("");
					// input.focusout();
				}
			},
			rewardsuccess(content) {
				let _this = this
				var obj = {
					content: content,
					extra: {
						user: this.inUser,
						type: 'say'
					}
				};
				_this.mchatRoom.sendMessage(obj, {
					onSuccess: function(message) {
						_this.showNewMessage(obj)
					},
					onError: function(errorCode, message) {
						console.log("发送聊天室消息失败", errorCode);
					}
				});
			},
			showNewMessage(obj) {
				if (obj && obj.content) {
					var content = obj.content
					// console.log(content)
					// content = content.replace(/\[#eml_qq(.+?)\#]/g, function($0, $1) {
					// 	return '<img class="emoji_icon" src="/resources/jQuery-emoji-master20160321/dist/img/qq/' + $1 + '.png"/>';
					// });
					content = RongChatRoom.symbolToHTML(content)
					console.log(content)
					let list = this.list;
					list.push({
						type: obj.extra.type,
						from_client_id: obj.extra.user ? obj.extra.user.userId : 0,
						from_client_name: obj.extra.user ? obj.extra.user.name : '',
						content: content,
						time: obj.extra.time ? obj.extra.time : '',
					})
					console.log(list)
					this.list = list

					this.$nextTick((res) => {
						this.scrollToBottom()
					})
				}
			},
			login() {
				let _this = this
				if (this.socketStatus === 'connected') {
					uni.closeSocket({
						success: () => {
							this.socketStatus = 'closed'
						}
					})
				} else {
					uni.connectSocket({
						url: 'wss://v100.wxqewm.cn:7274',
						success: (data) => {
							console.log(data)
							this.socketStatus = 'connected'
						},
						fail: (data) => {
							console.log(data)
							this.socketStatus = 'connected'
						}
					})
					uni.onSocketOpen(function(res) {
						console.log('WebSocket连接已打开！')
						_this.socketStatus = 'connected'
						_this.chat_onopen()
					})
					uni.onSocketError(function(res) {
						console.log('WebSocket连接打开失败，请检查！')
					})
					uni.onSocketMessage(message => {
						this.getMessage(message)
					})
				}
			},
			chat_onopen() {
				let login_data = {
					type: 'login',
					room_id: this.room_id,
					member_id: this.member ? this.member.id : 0,
					client_name: this.member ? this.member.nickname : ('游客' + parseInt(Math.random() * 100000)),
					client_thumb: this.member ? this.member.head_portrait : '',
				}
				console.log("websocket握手成功，发送登录数据:" + login_data)
				this.sendMessage(JSON.stringify(login_data))
				this.say('system', 0, '', '聊天消息登录成功！')
			},
			//关闭信道
			closeSocket() {
				if (this.socketStatus === 'connected') {
					uni.closeSocket({
						success: () => {
							this.socketStatus = 'closed'
						}
					})
				}
			},
			say(type, from_client_id, from_client_name, content, time) {
				console.log(content)
				content = content.replace(/\[#eml_qq(.+?)\#]/g, function($0, $1) {
					return '<img class="emoji_icon" style="width:20px;heigith:20px;" src="http://v91.wxqewm.cn/resources/jQuery-emoji-master20160321/dist/img/qq/' +
						$1 + '.png"/>';
				});

				let list = this.list;
				list.push({
					type: type,
					from_client_id: from_client_id,
					from_client_name: from_client_name,
					content: content,
					time: time,
				})
				this.list = list
				this.$nextTick((res) => {
					this.scrollToBottom()
				})
			},
			sendMessage(data) {
				this.onSubmit(data)
				// if (this.socketStatus === 'connected') {
				// 	uni.sendSocketMessage({
				// 		data: data
				// 	})
				// }
			},
			getMessage(message) {
				console.log(message)
				var data = JSON.parse(message.data)
				switch (data['type']) {
					// 服务端ping客户端
					case 'ping':
						this.sendMessage('{"type":"pong"}')
						break
						// 登录 更新用户列表
					case 'login':
						this.say('system', data['client_id'], data['client_name'], '<span style="color:orange;">' + data['client_name'] +
							'</span> 加入了聊天室', data['time'])
						var client_list = this.client_list
						if (data['client_list']) {
							console.log(data['client_list'])
							client_list = data['client_list']
						} else {
							client_list[data['client_id']] = {
								id: data['member_id'],
								name: data['client_name'],
								thumb: data['client_thumb']
							}
						}
						this.client_list = client_list

						this.clientChange()
						console.log(data['client_name'] + "登录成功")
						break
					case 'reward':
						this.say(data['type'], data['from_client_id'], data['from_client_name'], '<span style="color:orange;">' + data[
								'client_name'] +
							'</span>' + data['content'], data['time'])
						break
						// 发言
					case 'say':
						this.say(data['type'], data['from_client_id'], data['from_client_name'], data['content'], data['time'])
						break
						// 用户退出 更新用户列表
					case 'logout':
						//{"type":"logout","client_id":xxx,"time":"xxx"}
						this.say('system', data['from_client_id'], data['from_client_name'], '<span style="color:orange;">' + data[
								'from_client_name'] +
							'</span> 退出了', data['time'])
						var client_list = this.client_list
						delete client_list[data['from_client_id']]

						this.client_list = client_list
						this.clientChange()
						break
				}
			},
			clientChange() {
				this.$emit("pClientChange", this.client_list)
			},
			scrollToBottom: function() {
				let query = uni.createSelectorQuery()
				query.in(this).select('.comment-content').boundingClientRect()
				query.exec((res) => {
					this.scrollTop = res[0].height
				})
			},
			setHeight(height) {
				this.pHeight = height
			}
		},
	}
	// #endif
</script>

<style>
	.comment-content-scroll.video .comment-content {
		margin: 30rpx 0;
	}

	.comment-content-scroll.video .common-li {
		background-color: #FFF;
		color: #000000;
	}

	.comment-content-scroll {
		width: 100%;
	}

	.comment-content .common-li {
		background-color: rgb(0, 0, 0, 0.5);
		display: inline-block;
		color: #FFF;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.comment-content .common-li .name {
		color: orange;
	}

	.comment-content .common-li .cn {
		word-break: break-all;
	}

	.comment-content .common-li .cn img {
		width: 20px;
		height: 20px;
	}

	.comment-content .system,
	.comment-content-scroll.video .system {
		color: #ED1C24;
	}

	.comment-content .system .name {
		display: none;
	}
</style>
